#-*- coding:UTF-8 -*-
__author__ = 'Frank Yang <frankyang418@gmail.com>'
__date__ = "13-5-16 上午10:24"
__doc__ = u""
import tornado.escape


class FlashMessageMixin(object):
    _flashed_message_identity = 'flashed_messages'

    @property
    def messages(self):
        if self._flashed_message_identity in self.session:
            return tornado.escape.json_decode(self.session[self._flashed_message_identity])
        else:
            return []

    def _flash(self, message, category='success'):
        messages = self.messages
        messages.append([message, category])
        self.session[self._flashed_message_identity] = tornado.escape.json_encode(messages)

    def flash_error(self, message):
        self._flash(message, category='error')

    def flash_info(self, message):
        self._flash(message, category='success')

    def get_flashed_messages(self):
        messages = self.messages
        del self.session[self._flashed_message_identity]
        return messages

    def has_flashed_messages(self):
        return True if self.messages else False